package com.jf.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf.blog.bean.BlogTag;
import com.jf.blog.bean.Tag;
import com.jf.blog.form.tag.TagSearchForm;
import com.jf.blog.mapper.TagMapper;
import com.jf.blog.service.BlogTagService;
import com.jf.blog.service.TagService;
import com.jf.blog.util.LoginUtil;
import com.jf.blog.util.ResultJson;
import com.jf.blog.util.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author JF
 * @since 2025-06-20
 */
@Service
@Transactional
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    @Autowired
    private BlogTagService blogTagService;

    @Override
    public ResultJson getPage(int page, int limit, TagSearchForm searchForm) {
        IPage<Tag> iPage = this.page(new Page<>(page, limit),
                new QueryWrapper<Tag>()
                        .eq(searchForm.getCreateUserId() != null, "create_user", searchForm.getCreateUserId())
                        .eq(StringUtils.isNotEmpty(searchForm.getName()), "name", searchForm.getName())
                        .eq(searchForm.getStatus() != null, "status", searchForm.getStatus())
                        .orderByDesc("create_time")
        );
        return ResultJson.success(iPage);
    }

    @Override
    public void delete(List<Integer> tagIds) {
        this.removeByIds(tagIds);
        blogTagService.remove(new QueryWrapper<BlogTag>().in("tag_id", tagIds));
    }

    @Override
    public ResultJson select() {
        return ResultJson.success(this.list(
                new QueryWrapper<Tag>()
                        .eq("create_user", LoginUtil.getLoginUser().getUserinfoId())
                        .orderByDesc("create_time"))
        );
    }

    @Override
    public void updateStatus(int tagId) {
        Tag tag = this.getById(tagId);
        if (tag == null) {
            throw new BusinessException("编号不存在！");
        }
        tag.setStatus(tag.getStatus() == 1 ? 2 : 1);
        this.updateById(tag);
    }
}
